<template>
  <t-modal
    title="BIM图库"
    :width="988"
    :visible="visible"
    wrapClassName="t-popup-modal"
    @cancel="handleCancel"
    :footer="null"
    :destroyOnClose="true"
  >
    <div class="curve-modal-container">
      <a-upload
        :accept="accept"
        :file-list="[]"
        :beforeUpload="
          (file) => {
            return beforeUpload(file);
          }
        "
      >
        <a-button
          icon="upload"
          class="cu-btn-primary margin-bottom-xs"
          style="margin-left: 0"
        >
          点击上传
        </a-button>
      </a-upload>
      <div class="images-container">
        <div
          v-for="(item, index) in tableData"
          :key="item.uuid"
          @click.stop="handelImg(item, index)"
          :class="[item.active && 'active', 'img-item']"
          @mouseenter="handleMouseUserOver(item)"
          @mouseleave="handleMouseOut(item)"
        >
          <!-- 删除 -->
          <a-icon
            type="close-circle"
            theme="filled"
            :class="[item.delete && !item.active && 'amint', 'delete-icon']"
            @click.stop="handelDelete(item)"
          />
          <!-- 选中 -->
          <a-icon
            type="check-circle"
            theme="filled"
            class="active-icon"
            v-if="item.active"
          />
          <img
            class="image"
            style="width: 80px; height: 80px"
            :src="item.imageAddress"
            fit="contain"
          />
        </div>
      </div>
      <div class="pager-container">
        <a-pagination
          size="small"
          @change="onChange"
          :current="pager.page"
          :pageSize="pager.pageSize"
          :total="pager.total"
          :show-total="(total) => `共 ${total} 条`"
        />
      </div>
    </div>
  </t-modal>
</template>

<script>
import {
  uploadBimImage,
  saveImage,
  deleteImage,
  getImageList,
} from "@/api/bim";
export default {
  props: {
    visible: {
      type: Boolean,
      required: false,
    },
  },
  data() {
    return {
      accept: ".png,.PNG,.jpg,.JPG,.jpeg,.JPEG,.bmp,.BMP,.gif,.GIF",
      pager: {
        page: 1,
        pageSize: 24,
        total: 0,
      },
      tableData: [],
    };
  },
  watch: {
    visible: {
      handler(val) {
        this.$emit("update:visible", val);
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    //选中图片
    handelImg(item, index) {
      this.tableData.forEach((v) => {
        v.active = false;
      });
      item.active = !item.active;
      this.$emit("changeImg", { index, item });
      this.closeModal();
    },
    //删除图片
    handelDelete(row) {
      let dataLength = this.tableData.length;
      let that = this;
      that.$confirm({
        title: "提示",
        content: "此操作将永久删除该文件, 是否继续?",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          deleteImage({ uuid: row.uuid })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功", 1.5);
                if (dataLength == 1 && that.pager.page > 1) {
                  that.pager.page -= 1;
                }
                that.getData();
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },
    //查询图片列表
    getData() {
      return new Promise((resolve, reject) => {
        let { page, pageSize } = this.pager;
        getImageList({
          page: page,
          pageSize: pageSize,
        })
          .then((res) => {
            this.tableData = res?.rows || [];
            this.pager.total = res.totalCount ?? 0;
            this.tableData.forEach((v) => {
              this.$set(v, "delete", false);
              this.$set(v, "active", false);
            });
            resolve();
          })
          .catch((_) => {
            this.tableData = [];
            this.pager.total = 0;
            reject();
          });
      });
    },
    //图片上传
    beforeUpload(file) {
      let formData = new FormData();
      formData.append("file", file);
      uploadBimImage(formData)
        .then(async (res) => {
          let { url, object } = res;
          let { height, width } = await this.getImageSize(url);
          saveImage({
            imageName: object,
            height,
            width,
            imageAddress: url,
            size: "",
          })
            .then((obj) => {
              if (obj.statusCode === 200 || obj === 1) {
                this.$message.success(obj?.message ? obj?.message : "上传成功");
                this.getData();
              } else {
                this.$message.error(obj?.message ?? "上传失败");
              }
            })
            .catch((_) => {
              this.$message.error(obj?.message ?? "上传失败");
            });
        })
        .catch((_) => {});
      return false;
    },

    // 获取图片尺寸
    getImageSize(src) {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.onload = function() {
          const width = img.width;
          const height = img.height;
          resolve({ width, height });
        };
        img.onerror = function() {
          reject(new Error("无法加载图片"));
        };
        img.src = src;
      });
    },
    //分页切换
    onChange(page, pageSize) {
      this.pager.page = page;
      this.pager.pageSize = pageSize;
      this.getData();
    },

    //鼠标移入
    handleMouseUserOver(item) {
      this.tableData.forEach((v) => {
        v.delete = false;
      });
      item.delete = true;
    },
    //鼠标移除
    handleMouseOut(item) {
      this.tableData.forEach((v) => {
        v.delete = false;
      });
      item.delete = false;
    },
    //关闭弹窗
    handleCancel() {
      this.tableData = [];
      this.pager = {
        page: 1,
        pageSize: 24,
        total: 0,
      };
      this.$emit("update:visible", false);
    },
  },
};
</script>

<style lang="less" scoped>
.curve-modal-container {
  display: flex;
  flex-direction: column;
  height: 460px;
  .images-container {
    flex: 1;
    box-sizing: border-box;
    padding: 20px 0 10px 0px;
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    .img-item {
      position: relative;
      cursor: pointer;
      width: 104px;
      height: 104px;
      background: #f1f1f1;
      border-radius: 6px;
      margin: 0 16px 16px 0;
      display: flex;
      align-items: center;
      justify-content: center;
      .image {
        height: 80px;
        width: 80px;
        object-fit: contain;
      }
      &:nth-child(8n) {
        margin-right: 0;
      }
      &.active {
        background: rgba(23, 125, 220, 0.2);
        outline: 1px solid #0081ff;
      }
      &:hover {
        background: rgba(23, 125, 220, 0.2);
      }
      .active-icon {
        font-size: 16px;
        color: #177ddc;
        position: absolute;
        top: 8px;
        right: 8px;
      }

      .delete-icon {
        font-size: 16px;
        color: #ef6565;
        position: absolute;
        top: 8px;
        right: 8px;
        opacity: 0;
        transition: 0.5s;
        &.amint {
          opacity: 1;
          transition: 0.5s;
        }
      }
    }
  }
  .pager-container {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
